package com.loongtech.bi.action.realTime;

import com.loongtech.bi.entity.system.EntityBiChannel;
import com.loongtech.bi.manager.realTime.BossRealTimeManager;
import com.loongtech.bi.manager.realTime.PlatformAndServerRealTimeManager;
import com.loongtech.bi.manager.realTime.PlatformAndServerRealTimeManager.ChannelData;
import com.loongtech.bi.manager.realTime.PlatformAndServerRealTimeManager.ChannelHourData;
import com.loongtech.bi.manager.realTime.PlatformAndServerRealTimeManager.PlatformData;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.ConfigManager;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.manager.system.SysRoleChannelManager;
import com.loongtech.bi.support.Session;
import com.loongtech.bi.support.chart.ChartTool;
import com.loongtech.bi.support.chart.ChartUIData;
import com.loongtech.core.util.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;
import java.util.Map.Entry;

/**
 * 实时数据-分渠道概况Action
 * @author Marin
 * @date 2015年09月17日
 */
@Controller
@Scope("view")
public class PlatformAndChannelRealTimeAction {
	private Date lookDate = new Date(Time.getBeginningOfDay(Time.currentTime()));  // 前端传过来的查看时间
	
	private List<PlatformData> platformDatas;
	private PlatformData allPlatformData;
	private List<ChannelData> allChannelDatas;
	private List<ChannelData> channelDatas;
    private List<ChannelData> retlist;  // cps数据

	private String lastUpdateTimeStr = "";  // 前端要访问的最近更新时间字符串
	private String selectedPlatform = "all";
	
	private String selectZhiBiaoItem = "newUser";
	@SuppressWarnings("serial")
	/*private LinkedHashMap<String, String> allZhiBiaoItmes = new LinkedHashMap<String, String>() {
		{put("新增账号数", "newUser"); put("活跃账号数", "activeUser"); put("付费账号数", "payUser"); 
		 put("付费金额", "pay"); put("新增账号付费人数", "newPayUser"); put("新增账号付费金额", "newPay"); put("新增账号付费金额", "newPay"); put("活跃付费率", "activePayRadio");}};*/
    private LinkedHashMap<String, String> allZhiBiaoItmes = new LinkedHashMap<String, String>() {
        {put("新增账号数", "newUser");  put("付费账号数", "payUser"); put("付费金额", "pay"); put("新增账号付费人数", "newPayUser"); put("新增账号付费金额", "newPay"); put("新增账号付费金额", "newPay");}};

    private List<ChannelHourData> channelHourDatas;
	private List<Map<Integer, String>> hourDatas;

    public static Map<String, Map<String, String>> activatePlatformData = new HashMap<>();
    public static Map<String, String> activateAllPlatformData = new HashMap<>();
    public static Map<String, Map<String, String>> activateChannelData = new HashMap<>();

    private Map<String, String> channelItmes;  // 渠道下拉列表
    private List<String> selectedChannels; // 在线选中的渠道
    private List<PlatformAndServerRealTimeManager.ChannelOnlineRealTimeData> channelOnlineRealTimeDatas;
    private ChartUIData channelOnlineRealTimeChart;
	
	@Autowired
	PlatformAndServerRealTimeManager manager;
    @Autowired
    private BossRealTimeManager bossRealTimeManager;
    @Autowired
    ConfigManager configManager;
	@Autowired
	SysLogManager sysLogManager;
    @Resource
    SysRoleChannelManager sysRoleChannelManager;
    @Resource
    Session session;
	
	@SuppressWarnings({ "serial" })
	private Map<Integer, String> hourMap = new HashMap<Integer, String>() {
		{
			put(0, "00:00~00:59");
			put(1, "01:00~01:59");
			put(2, "02:00~02:59");
			put(3, "03:00~03:59");
			put(4, "04:00~04:59");
			put(5, "05:00~05:59");
			put(6, "06:00~06:59");
			put(7, "07:00~07:59");
			put(8, "08:00~08:59");
			put(9, "09:00~09:59");
			put(10, "10:00~10:59");
			put(11, "11:00~11:59");
			put(12, "12:00~12:59");
			put(13, "13:00~13:59");
			put(14, "14:00~14:59");
			put(15, "15:00~15:59");
			put(16, "16:00~16:59");
			put(17, "17:00~17:59");
			put(18, "18:00~18:59");
			put(19, "19:00~19:59");
			put(20, "20:00~20:59");
			put(21, "21:00~21:59");
			put(22, "22:00~22:59");
			put(23, "23:00~23:59");
		}
	};
	
	@PostConstruct
	public void init() {
        List<EntityBiChannel> list = BiPlatformManager.CHANNEL_LIST;
        selectedChannels = new ArrayList<>();
        channelItmes = new LinkedHashMap<>();
        for (int i = list.size() - 1; i >= 0; i--) {
            EntityBiChannel t = list.get(i);

            channelItmes.put(t.getName(), t.getId());

            if (selectedChannels.size() < 3) {
                selectedChannels.add(t.getId());
            }
        }

		search();
	}
	
	public void search() {
		sysLogManager.addLog(session.getUserName(), "实时数据-分渠道概况");
		
		platformDatas = new ArrayList<>();
		allPlatformData = manager.new PlatformData();
		allChannelDatas = new ArrayList<>();
		channelDatas = new ArrayList<>();
		hourDatas = new ArrayList<>();
        channelOnlineRealTimeChart = null;
		
		/*int d = Time.getInterval(lookDate, new Date());
		if (d > 7 || d < 0) {
			context.addMessage(null, new FacesMessage("查看日期错误", "只能查询七天内的数据!"));
			return;
		}*/

        //manager.getSession().clear();

        long lastupdatetime = bossRealTimeManager.getMaxUpdateTime();
        lastUpdateTimeStr = "最近一次更新时间为：" + Time.getCeil1(lastupdatetime);
		/*long lastupdatetime = Time.getBeginningOfDay(-1) > lookDate.getTime() ? Time.getBeginningOfDay(lookDate.getTime() + Time.DAY) : System.currentTimeMillis();
		lastUpdateTimeStr = "最近一次更新时间为：" + Time.getCeil5(lastupdatetime);*/

		manager.updateDatas(lookDate, platformDatas, allPlatformData, allChannelDatas);
		if (!allPlatformData.isNotempty()) {
			allPlatformData = null;
		} else {
            /*String ds = Time.getDateStr(lookDate);

            String url = configManager.getConfigValueByName(ConfigManager.ALL_ACTIVATE_URL);
            if (url != null) {
                AsyncHttpClientUtils.asyncSendAllPlatformActiveDataRequest(url + ds, ds);
                allPlatformData.setActivate(activateAllPlatformData.get(ds) == null ? "-" : activateAllPlatformData.get(ds));
            } else {
                System.out.println("需要配置ALL_ACTIVATE_URL");
            }
            url = configManager.getConfigValueByName(ConfigManager.PLATFORM_CHANNEL_URL);
            if (url != null) {
                AsyncHttpClientUtils.asyncSendPlatformActiveDataRequest(url + ds, ds);
                Map<String, String> pm = activatePlatformData.get(ds);
                if (pm == null) {
                    pm = new HashMap<>();
                    activatePlatformData.put(ds, pm);
                }

                for (PlatformData p : platformDatas) {
                    p.setActivate(pm.get(p.getPlatformid()) == null ? "-" : pm.get(p.getPlatformid()));
                }
            } else {
                System.out.println("需要配置PLATFORM_CHANNEL_URL");
            }
            url = configManager.getConfigValueByName(ConfigManager.CHANNEL_ACTIVATE_URL);
            if (url != null) {
                Map<String, String> cm = activateChannelData.get(ds);
                if (cm == null) {
                    cm = new HashMap<>();
                    activateChannelData.put(ds, cm);
                }

                AsyncHttpClientUtils.asyncSendChannelActiveDataRequest(url + ds, ds);
                for (ChannelData c : allChannelDatas) {
                    c.setActivate(cm.get(c.getChannelid()) == null ? "-" : cm.get(c.getChannelid()));
                }
            } else {
                System.out.println("需要配置CHANNEL_ACTIVATE_URL");
            }*/


            channelOnlineRealTimeDatas = manager.getChannelOnlineRealTimeDatas(lookDate, selectedChannels);
            if (channelOnlineRealTimeDatas != null && channelOnlineRealTimeDatas.size() > 0) {
                channelOnlineRealTimeChart = new ChartUIData();
                channelOnlineRealTimeChart.setSelectItem("online");
                channelOnlineRealTimeChart.setJsonStr(new ChartTool(channelOnlineRealTimeDatas, PlatformAndServerRealTimeManager.ChannelOnlineRealTimeData.class, channelOnlineRealTimeChart.getSelectItem()).loadData(channelOnlineRealTimeChart.getJsonType()));
            } else {
                channelOnlineRealTimeChart = null;
            }
            selectPlatform();
        }

        getChannelDatasByUser();
	}

    public void handleChannelsChange() {
        channelOnlineRealTimeDatas = manager.getChannelOnlineRealTimeDatas(lookDate, selectedChannels);

        if (channelOnlineRealTimeDatas != null && channelOnlineRealTimeDatas.size() > 0) {
            channelOnlineRealTimeChart = new ChartUIData();
            channelOnlineRealTimeChart.setSelectItem("online");
            channelOnlineRealTimeChart.setJsonStr(new ChartTool(channelOnlineRealTimeDatas, PlatformAndServerRealTimeManager.ChannelOnlineRealTimeData.class, channelOnlineRealTimeChart.getSelectItem()).loadData(channelOnlineRealTimeChart.getJsonType()));
        } else {
            channelOnlineRealTimeChart = null;
        }
    }

    public void selectPlatform() {
        channelDatas = new ArrayList<>();
        if (allChannelDatas != null && allChannelDatas.size() > 0) {
            if ("all".equals(selectedPlatform)) {
                channelDatas = allChannelDatas;
                Collections.sort(channelDatas, manager.new ChannelData().comparator2);
            } else {
                for (ChannelData c : allChannelDatas) {
                    String pid = BiPlatformManager.CHANNEL_PLATFORM_MAP.get(c.getChannelid());
                    if (pid != null && pid.equals(selectedPlatform)) {
                        channelDatas.add(c);
                    }
                }
                Collections.sort(channelDatas, manager.new ChannelData().comparator);
            }

            getChannelDatasByUser();
        }
        handleZhiBiaoChange();
    }

	public void handleZhiBiaoChange() {
		channelHourDatas = new ArrayList<>();
		hourDatas = new ArrayList<>();
		manager.updateChannelHourDatas(lookDate, selectZhiBiaoItem, selectedPlatform, channelHourDatas);
		
		Set<Integer> t = new HashSet<>(); // 用于补齐数据
		for (ChannelHourData s : channelHourDatas) {
			hourDatas.add(s.getDatas());
			for (int i : s.getDatas().keySet()) {
				t.add(i);
			}
		}
		for (Map<Integer, String> h : hourDatas) {
			for (int tt : t) {
				if (h.get(tt) == null) {
					h.put(tt, "");
				}
			}
			sortMapByKey(h);
		}
	}
	
	public static void sortMapByKey(Map<Integer, String> map) {  
        if (map == null || map.isEmpty()) {  
            return;  
        }  
        Map<Integer, String> sortMap = new TreeMap<Integer, String>(new PlatformAndChannelRealTimeAction().new MapKeyComparator());  
        sortMap.putAll(map); 
        map.clear();
        map.putAll(sortMap);
	}  
  
	//比较器类  
	public class MapKeyComparator implements Comparator<Integer>{  
	    public int compare(Integer str1, Integer str2) {  
	        return str2.compareTo(str1);  
	    }  
	}  
	
	public String getHourStr(int hour){
		if(hour < 0 || hour >23){
			return "";
		}
		return hourMap.get(hour);
	}
	
	public Set<Integer> getColumnNames(int i) {
		return hourDatas.size() > 0 ? hourDatas.get(i).keySet() : new HashSet<Integer>();
	}
	
	public String getColumnValue(int rowindex, int i) {
		ArrayList<String> l = new ArrayList<String>(hourDatas.get(rowindex).values());
		return i > l.size() - 1 ? "" : l.get(i);
	}
	
	public List<String> getColumnValues(int rowindex) {
		return new ArrayList<>(hourDatas.get(rowindex).values());
	}
	
	public String getFacetHeader() {
		String result = "";
		for (Entry<String, String> entry : allZhiBiaoItmes.entrySet()) {
			if (selectZhiBiaoItem.equals(entry.getValue())) {
				result = entry.getKey();
				break;
			}
		}
		
		return result;
	}

	public void getChannelDatasByUser() {
		retlist = new ArrayList<>();
		List<ChannelData> allList = getChannelDatas();
		Set<String> selectedSet = sysRoleChannelManager.getChannelSetByUserId(session.getUserId());
		if (null == selectedSet || selectedSet.isEmpty() || null == allList || allList.isEmpty()) {
			return;
		}

		for (ChannelData info : allList) {
			if (selectedSet.contains(info.getChannelid())) {
				retlist.add(info);
			}
		}
	}

    public List<ChannelHourData> getChannelHourDatasByUser() {
    	List<ChannelHourData> retlist = new ArrayList<>();
        List<ChannelHourData> allList = getChannelHourDatas();
        Set<String> selectedSet = sysRoleChannelManager.getChannelSetByUserId(session.getUserId());
        System.out.println(selectedSet);
        if (null == selectedSet || selectedSet.isEmpty() || null == allList || allList.isEmpty()) {
			return retlist;
		}
        
        for(ChannelHourData info : allList){
        	if (selectedSet.contains(info.getChannelid())) {
				retlist.add(info);
			}
        }
        return retlist;
    }
	
	// left = 2 3 7
	public String getLeftDate(int left) {
		return Time.formatTime(lookDate.getTime() - Time.DAY * (left - 1), "MM-dd");
	}
	
	public Date getLookDate() {
		return lookDate;
	}

	public void setLookDate(Date lookDate) {
		this.lookDate = lookDate;
	}

	public List<PlatformData> getPlatformDatas() {
		return platformDatas;
	}

	public void setPlatformDatas(List<PlatformData> platformDatas) {
		this.platformDatas = platformDatas;
	}

	public PlatformData getAllPlatformData() {
		return allPlatformData;
	}

	public void setAllPlatformData(PlatformData allPlatformData) {
		this.allPlatformData = allPlatformData;
	}

	public List<ChannelData> getChannelDatas() {
		return channelDatas;
	}

	public void setChannelDatas(List<ChannelData> channelDatas) {
		this.channelDatas = channelDatas;
	}

	public String getLastUpdateTimeStr() {
		return lastUpdateTimeStr;
	}

	public void setLastUpdateTimeStr(String lastUpdateTimeStr) {
		this.lastUpdateTimeStr = lastUpdateTimeStr;
	}

	public String getSelectedPlatform() {
		return selectedPlatform;
	}

	public void setSelectedPlatform(String selectedPlatform) {
		this.selectedPlatform = selectedPlatform;
	}

	public List<ChannelData> getAllChannelDatas() {
		return allChannelDatas;
	}

	public void setAllChannelDatas(List<ChannelData> allChannelDatas) {
		this.allChannelDatas = allChannelDatas;
	}

	public String getSelectZhiBiaoItem() {
		return selectZhiBiaoItem;
	}

	public void setSelectZhiBiaoItem(String selectZhiBiaoItem) {
		this.selectZhiBiaoItem = selectZhiBiaoItem;
	}

	public LinkedHashMap<String, String> getAllZhiBiaoItmes() {
		return allZhiBiaoItmes;
	}

	public void setAllZhiBiaoItmes(LinkedHashMap<String, String> allZhiBiaoItmes) {
		this.allZhiBiaoItmes = allZhiBiaoItmes;
	}

	public List<ChannelHourData> getChannelHourDatas() {
		return channelHourDatas;
	}

	public void setChannelHourDatas(List<ChannelHourData> channelHourDatas) {
		this.channelHourDatas = channelHourDatas;
	}

	public List<Map<Integer, String>> getHourDatas() {
		return hourDatas;
	}

	public void setHourDatas(List<Map<Integer, String>> hourDatas) {
		this.hourDatas = hourDatas;
	}

    public List<String> getSelectedChannels() {
        return selectedChannels;
    }

    public void setSelectedChannels(List<String> selectedChannels) {
        this.selectedChannels = selectedChannels;
    }

    public ChartUIData getChannelOnlineRealTimeChart() {
        return channelOnlineRealTimeChart;
    }

    public void setChannelOnlineRealTimeChart(ChartUIData channelOnlineRealTimeChart) {
        this.channelOnlineRealTimeChart = channelOnlineRealTimeChart;
    }

    public Map<String, String> getChannelItmes() {
        return channelItmes;
    }

    public void setChannelItmes(Map<String, String> channelItmes) {
        this.channelItmes = channelItmes;
    }

    public List<ChannelData> getRetlist() {
        return retlist;
    }

    public void setRetlist(List<ChannelData> retlist) {
        this.retlist = retlist;
    }
}
